import os
import sys
import time
from multiprocessing import Process

def SubmitJob(jobName, device_ids):
    log_line = f"[{time.strftime('%Y-%m-%d %H:%M:%S')}]: {jobName} start!"
    print(log_line)
    os.system("rm {}".format(jobName.replace('.py', '.log')))
    os.system(f"CUDA_VISIBLE_DEVICES={device_ids} python {jobName} >> {jobName.replace('.py', '.log')}")
    log_line = f"[{time.strftime('%Y-%m-%d %H:%M:%S')}]: {jobName} end!"
    print(log_line)

dir = "./"
dir_path = os.path.abspath(dir)
files = os.listdir(dir_path)
py_files = [fname for fname in files if ("MME_" in fname) and ("_FS100.py" in fname)]
py_files.sort()

process_list = []
start_idx = 0
for device_id, idx in enumerate(range(start_idx, min(len(py_files), start_idx+8))):
    p = Process(target=SubmitJob, args=(py_files[idx], f'{device_id}', ))
    p.start()
    process_list.append(p)

for p in process_list:
    p.join()
